package com.h2.ref.server.util.jetty;

import java.lang.management.ManagementFactory;
import java.util.HashMap;
import java.util.Map;

import javax.management.MBeanServer;

import org.mortbay.jetty.Server;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.webapp.WebAppContext;
import org.mortbay.management.MBeanContainer;

/**
 * EndPoint implementation which accepts input via a SocketServer. Used for
 * quick development without more advanced server tools like Tomcat or Jetty.
 */
public final class JettyEndpoint {
   
   private JettyEndpoint() {
      //do nothing
   }
   
   public static void main(String[] args) {
      
      //args to map
      Map<String, String> argMap = new HashMap<String, String>(args.length);
      String[] arg = null;
      for (int i = 0; i < args.length; i++) {
         arg = args[i].split("=");
         if(arg == null || arg.length < 2) {
            System.err.println("Not a pair: " + args[i]);
            continue;
         }
         argMap.put(arg[0], arg[1]);
      }
      
      //port
      int port = 8080;
      if (argMap.containsKey("port")) {
         port = Integer.parseInt(argMap.get("port"));
      }
      
      //path
      String path = "/";
      if (argMap.containsKey("context")) {
         path = argMap.get("context");
         if (!path.startsWith("/")) {
            path = "/" + path;
         }
      }
      
      //war directory
      String webDir = "web";
      if (argMap.containsKey("web.dir")) {
         webDir = argMap.get("web.dir");
      }
      
      Server server = new Server();
      SelectChannelConnector connector = new SelectChannelConnector();
      
      
      connector.setPort(port);
      server.addConnector(connector);

      WebAppContext web = new WebAppContext();
      web.setClassLoader(JettyEndpoint.class.getClassLoader());
      web.setContextPath(path);
      
      web.setWar(webDir);
      server.addHandler(web);

      MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
      MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
      server.getContainer().addEventListener(mBeanContainer);
      mBeanContainer.start();
      try {
        server.start();
        server.join();
      } catch (Exception exp) {
         //CHECKSTYLE IGNORE: RegexpSinglelineJava 1
        exp.printStackTrace();
        System.exit(100);
      }
      
   }

}
